package pl.squeaky.mvc.util;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;

import pl.squeaky.mvc.nature.MvcNature;

final public class SelectionUtils {
	private SelectionUtils() {
	}
	
	public static IProject getMvcProject(ISelection selection) {
		IProject project = null;
		if(selection instanceof IStructuredSelection) {
			IStructuredSelection structuredSelection = (IStructuredSelection)selection;
			
			Object element = structuredSelection.getFirstElement();
			if(element instanceof IResource) {
				IResource resource = (IResource)element;
				
				project = resource.getProject();
			}
			
			try {
				if(project != null
				   && !project.hasNature(MvcNature.NATURE_ID)) {
					project = null;
				}
			} catch (CoreException e) {
				throw new RuntimeException(e);
			}
		}
		
		return project;
	}
	
	public static MvcNature getMvcNature(ISelection selection) {
		IProject project = getMvcProject(selection);
		if(project != null) {
			try {
				return (MvcNature)project.getNature(MvcNature.NATURE_ID);
			} catch (CoreException e) {
				throw new RuntimeException(e);
			}
		} else {
			return null;
		}
	}
}
